package com.scs.application.modules.fsd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.PinYinUtils;
import com.scs.application.modules.fsd.dto.SaveRoleDTO;
import com.scs.application.modules.fsd.entity.*;
import com.scs.application.modules.fsd.mapper.FsdRoleMapper;
import com.scs.application.modules.fsd.service.FsdRoleService;
import com.scs.application.modules.fsd.service.GroupRoleService;
import com.scs.application.modules.fsd.service.GroupUserService;
import com.scs.application.modules.fsd.service.UserRoleService;
import com.scs.application.modules.sys.entity.Authority;
import com.scs.application.modules.sys.service.AuthorityService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class FsdRoleServiceImpl extends BaseServiceImpl<FsdRoleMapper, FsdRole> implements FsdRoleService {
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    GroupUserService groupUserService;
    @Autowired
    GroupRoleService groupRoleService;
    @Autowired
    AuthorityService authorityService;

    @Override
    @Transactional
    public Boolean removeRole(List<String> roleIds) {
        for (String roleId : roleIds) {
            // 清除角色权限
            authorityService.remove(new QueryWrapper<Authority>()
                    .eq("target_id", roleId)
                    .eq("target_type", "R"));
            // 清除角色成员
            userRoleService.remove(new QueryWrapper<FsdUserRole>()
                    .eq("role_id", roleId));
            removeById(roleId);
        }
        return true;
    }

    @Override
    public List<FsdRole> listUserRole(String userId) {
        List<FsdUserRole> roleUsers = userRoleService.list(new QueryWrapper<FsdUserRole>()
                .eq("user_id", userId));

        Collection<FsdRole> roles = Lists.newArrayList();
        if (!roleUsers.isEmpty()) {
            Collection<String> roleIds = roleUsers.stream().map(o -> o.getRoleId()).collect(Collectors.toList());
            roles = listByIds(roleIds);
        }

        // 是否包含 everyone用户组
        long count = roles.stream().filter(r -> "everyone".equalsIgnoreCase(r.getRoleKey())).count();
        if (count == 0) {
            FsdRole everyoneRole = this.getOne(new QueryWrapper<FsdRole>().eq("role_key", "everyone"));
            if (everyoneRole != null) {
                roles.add(everyoneRole);
            }
        }
        return (List<FsdRole>) roles;
    }

    @Override
    public String saveRole(SaveRoleDTO para){
        FsdRole role=new FsdRole();
        role.setRoleKey(para.getRoleKey());
        role.setRoleName(para.getRoleName());
        role.setRoleNamePy(PinYinUtils.getAlpha(para.getRoleName()));
        role.setRemark(para.getRemark());
        save(role);
        return role.getId();
    }

    @Override
    public Map<String, Object> getRoleList(String keyword, Integer currentPage, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("count", this.count(Wrappers.<FsdRole>query().like("role_key", keyword).or().like("role_name", keyword).or().like("role_name_py", keyword)));
        map.put("rows", this.list(
                Wrappers.<FsdRole>query().like("role_key", keyword).or().like("role_name", keyword).or().like("role_name_py", keyword).last("limit " + (currentPage - 1) * pageSize + "," + pageSize).orderByDesc("id")
        ));
        return map;
    }

    @Override
    public Boolean editRole(SaveRoleDTO roleDTO) {
        FsdRole role = getById(roleDTO.getId());
        role.setRemark(roleDTO.getRemark());
        role.setRoleKey(roleDTO.getRoleKey());
        role.setRoleName(roleDTO.getRoleName());
        role.setRoleNamePy(PinYinUtils.getAlpha(roleDTO.getRoleName()));
        this.updateById(role);
        return true;
    }

    @Override
    public List<FsdRole> listRoleByUserId(String userId) {
        List<String> roleIds = new ArrayList<String>();//用户直接分配的权限
        List<String> groupRoleIds = new ArrayList<String>();//用户组包含的的权限
        List<FsdUserRole> roleUsers =userRoleService.list(new QueryWrapper<FsdUserRole>()
                .eq("user_id", userId));
        if (!roleUsers.isEmpty()) {
            roleIds=roleUsers.stream().map(o -> o.getRoleId()).collect(Collectors.toList());
        }
        List<FsdGroupUser> groupUsers = groupUserService.list(new QueryWrapper<FsdGroupUser>()
                .eq("user_id", userId));
        if (!groupUsers.isEmpty()) {
            Collection<String> groupIds = groupUsers.stream().map(o -> o.getGroupId()).collect(Collectors.toList());
            List<FsdGroupRole> groupRoles = groupRoleService.list(new QueryWrapper<FsdGroupRole>()
                    .in("group_id", groupIds));
            groupRoleIds = groupRoles.stream().map(o -> o.getRoleId()).collect(Collectors.toList());
        }
        Collection unionRoleIds = CollectionUtils.union(roleIds,groupRoleIds);
        Collection<FsdRole> roles = Lists.newArrayList();
        if (!unionRoleIds.isEmpty()) {
            roles = listByIds(unionRoleIds);
        }

//        // 是否包含 everyone用户组
//        long count = roles.stream().filter(r -> "everyone".equalsIgnoreCase(r.getCode())).count();
//        if (count == 0) {
//            Role everyoneRole = this.getOne(new QueryWrapper<Role>().eq("code", "everyone"));
//            if (everyoneRole != null) {
//                roles.add(everyoneRole);
//            }
//        }
        return (List<FsdRole>) roles;
    }
}
